<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
        }
        #messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #eee;
            padding: 10px;
            margin-bottom: 20px;
            background-color: #f9f9f9;
        }
        .user-message {
            text-align: right;
            color: blue;
            margin-bottom: 10px;
        }
        .ai-message {
            text-align: left;
            color: green;
            margin-bottom: 10px;
        }
        input {
            width: 70%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .log {
            margin-top: 20px;
            padding: 10px;
            background-color: #000;
            color: #0f0;
            font-family: monospace;
            height: 200px;
            overflow-y: auto;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>SSE连接测试</h1>
        <div id="messages"></div>
        <div>
            <input type="text" id="messageInput" placeholder="输入消息...">
            <button id="sendBtn">发送</button>
            <button id="cancelBtn" disabled>取消</button>
        </div>
        <div class="log" id="log"></div>
    </div>

    <script>
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const messagesDiv = document.getElementById('messages');
        const logDiv = document.getElementById('log');
        
        let xhr = null;
        // 使用固定的memoryId值，与后端示例一致
        const memoryId = '1';
        
        // 日志函数
        function log(message) {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.textContent = `[${timestamp}] ${message}`;
            logDiv.appendChild(logEntry);
            logDiv.scrollTop = logDiv.scrollHeight;
            console.log(`[SSE测试] ${message}`);
        }
        
        // 添加消息到界面
        function addMessage(type, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = type === 'user' ? 'user-message' : 'ai-message';
            messageDiv.textContent = content;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 发送消息函数
        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) {
                log('消息不能为空');
                return;
            }
            
            // 取消之前的请求
            if (xhr) {
                xhr.abort();
                xhr = null;
            }
            
            addMessage('user', message);
            messageInput.value = '';
            sendBtn.disabled = true;
            cancelBtn.disabled = false;
            
            log(`发送消息: ${message}`);
            log(`MemoryId: ${memoryId}`);
            
            // 创建新的XMLHttpRequest
            xhr = new XMLHttpRequest();
            
            // 使用相对路径，通过Vite代理
            const url = '/api/ai/chat';
            log(`请求URL: ${url}`);
            
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Accept', 'text/event-stream');
            
            // 进度事件处理
            xhr.onprogress = function() {
                const responseText = xhr.responseText;
                log(`收到响应数据: ${responseText.length} 字符`);
                
                // 简单处理SSE格式
                const lines = responseText.split('\n');
                let aiContent = '';
                
                for (const line of lines) {
                    if (line.startsWith('data:')) {
                        const data = line.substring(5).trim();
                        if (data) {
                            aiContent += data;
                            log(`提取到data: ${data}`);
                        }
                    }
                }
                
                if (aiContent) {
                    const aiMessageElements = messagesDiv.querySelectorAll('.ai-message');
                    if (aiMessageElements.length > 0) {
                        aiMessageElements[aiMessageElements.length - 1].textContent = aiContent;
                    } else {
                        addMessage('assistant', aiContent);
                    }
                }
            };
            
            // 加载完成事件
            xhr.onload = function() {
                log(`请求完成，状态码: ${xhr.status}`);
                sendBtn.disabled = false;
                cancelBtn.disabled = true;
                xhr = null;
            };
            
            // 错误事件
            xhr.onerror = function() {
                log(`请求错误，状态: ${xhr.status}`);
                addMessage('assistant', `错误: 网络请求失败，状态码: ${xhr.status}`);
                sendBtn.disabled = false;
                cancelBtn.disabled = true;
                xhr = null;
            };
            
            // 超时事件
            xhr.ontimeout = function() {
                log('请求超时');
                addMessage('assistant', '错误: 请求超时');
                sendBtn.disabled = false;
                cancelBtn.disabled = true;
                xhr = null;
            };
            
            // 设置超时
            xhr.timeout = 60000;
            
            // 准备请求体 - 完全按照后端示例格式
            const requestBody = JSON.stringify({
                "memoryId": "1",
                "message": message
            });
            log(`准备发送请求体: ${requestBody}`);
            
            log(`请求体: ${requestBody}`);
            
            // 发送请求
            try {
                xhr.send(requestBody);
                log('请求已发送');
            } catch (error) {
                log(`发送请求时异常: ${error.message}`);
                sendBtn.disabled = false;
                cancelBtn.disabled = true;
            }
        }
        
        // 取消请求函数
        function cancelRequest() {
            if (xhr) {
                log('取消请求');
                xhr.abort();
                xhr = null;
            }
            sendBtn.disabled = false;
            cancelBtn.disabled = true;
        }
        
        // 事件监听
        sendBtn.addEventListener('click', sendMessage);
        cancelBtn.addEventListener('click', cancelRequest);
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        log('测试页面已加载');
        log('使用Vite代理: /api -> http://localhost:8081/api');
    </script>
</body>
</html>